<template>
  <div class="split_preview">
    <el-dialog
      title="拆分结果确认"
      width="95%"
      top="10%"
      :visible.sync="dialogTableVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog"
      @closed="closeCallback"
      v-loading="isLoading">
      <div class="tables_panel">
        <div class="table_panel table_container table_work_order">
          <p class="table_title_item">工单表</p>
          <el-table
            :data="workorderList"
            height="250"
            border
            ref="multipleTable"
            @row-click="(row) => $refs.multipleTable.toggleRowSelection(row)"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            class="table_dialog">
            <el-table-column
              align="center"
              type="selection"
              :disabled="true"
              className="col_check"
              fixed="left"
              width="40">
            </el-table-column>
            <el-table-column
              prop="number"
              label="工单编号"
              align="center"
              min-width="200"
              fixed="left"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="drawingNumber"
              label="图号"
              align="center"
              min-width="80"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="materialNumber"
              label="物料编码"
              min-width="80"
              align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="materialName"
              label="物料名称"
              min-width="100"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="planQuantity"
              min-width="90"
              label="未拆分数量">
              <template slot-scope="scope">
                <span class="self_item">{{scope.row.planQuantity - scope.row.spiltQuantity}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="splitNumber"
              :resizable="false"
              label="拆分数量"
              class="data_td"
              align="center"
              min-width="90"
              show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </div>
        <div class="table_panel table_container ">
          <p class="table_title_item">批次清单表</p>
          <el-table
            :data="currentBatchList"
            @row-click="currentChange"
            height="250"
            border
            style="width: 100%"
            class="table_dialog">
            <el-table-column
              width="40"
              align="center"
              fixed="left">
              <template slot-scope="scope">
                <el-radio
                  v-model="turnoverBatchRadio"
                  :label="scope.row.id"
                  @change="getCurrentTurnoverBatch">
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              prop="number"
              label="周转码"
              min-width="240"
              fixed="left"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              min-width="50"
              prop="productionQuantity"
              align="center"
              label="数量"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              min-width="110"
              prop="planStartDate"
              align="center"
              label="计划开始时间"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="errorDateClass(scope.row.planStartDate)">{{scope.row.planStartDate | timeFormat}}</span>
              </template>
            </el-table-column>
            <el-table-column
              min-width="110"
              prop="planEndDate"
              align="center"
              label="计划完成时间"
              size="small"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="errorDateClass(scope.row.planEndDate)">{{scope.row.planEndDate | timeFormat}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="weekPlanName"
              :resizable="false"
              label="周计划"
              min-width="240"
              show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </div>
        <div class="table_panel table_container turnoverList">
          <p class="table_title_item">工序表</p>
          <el-table
            :data="currentWorkStageList"
            height="250"
            border
            style="width: 100%"
            class="table_dialog">
            <el-table-column
              :class-name="'static_col'"
              prop="sort"
              label="工序序号"
              width="80"
              align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              :class-name="'static_col'"
              prop="workstageName"
              label="工序名称"
              min-width="120"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              :class-name="'static_col'"
              prop="productionQuantity"
              label="投产数量"
              width="90"
              align="center"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              :class-name="'transparent_col'"
              prop="startDate"
              :resizable="false"
              min-width="270"
              label="计划时间">
              <template slot-scope="scope">
                <el-date-picker
                  size="small"
                  type="daterange"
                  className="plan_date"
                  :clearable="false"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="scope.row.planDate"
                  @change="handleChangePlanDate"
                  :picker-options="getPickerOptionsStart(scope.row.endPlanEndTime)"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right">
                </el-date-picker>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer mes_btn">
        <el-button @click.native.prevent="goBackPrev">
            返回上一步
          </el-button>
          <el-button type="primary" @click="submitDivideData">
            提交
          </el-button>
          <el-button @click.native.prevent="closePage">
            取消
          </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SplitPreview',
  props: {
    listData: Object
  },
  data() {
    return {
      selectItems: [], // 选中的数据
      dialogTableVisible: false, // 弹窗是否开启
      turnoverBatchRadio: '', // 批次清单索引
      currentBatchList: [], // 当前批次清单列表
      currentWorkStageList: [], // 当前工序列表
      isLoading: false, // 是否提交中
    }
  },
  computed: {
    // 工单list
    workorderList() {
      return this.listData.workorderList || []
    },
    // 周转清单list
    turnoverBatchList() {
      let turnover = this.listData.turnoverBatchList || []
      turnover.forEach((item) => {
        if (item.createBy && item.createBy['company']) {
          delete item.createBy['company']
        }
        if (item.createBy && item.createBy['office']) {
          delete item.createBy['office']
        }
      })
      return turnover
    },
    // 工序list
    workorderWorkstageList() {
      let workorderWorkstageList = this.listData.workorderWorkstageList || []
      workorderWorkstageList.map(item => {
        item.productionQuantity = this.turnoverBatchList.find(batch => batch.id === item.turnoverBatchId).productionQuantity
        this.$set(item, 'planDate', [item.startDate, item.endDate])
      })
      return workorderWorkstageList
    },
    currentDate() {
      return this.$startTimeStamp(window.serverTime)
    }
  },
  methods: {
    // 开启、关闭弹窗
    switchDialog(value) {
      this.dialogTableVisible = value
      if (value) {
        this.$nextTick(() => {
          this.workorderList.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        })
      }
    },
    currentChange(row) {
      if (row) {
        this.turnoverBatchRadio = row.id
        this.getCurrentTurnoverBatch()
      }
    },
    // 选完工序时间后，更新批次时间
    handleChangePlanDate(dateArr) {
      let currentBatch = this.currentBatchList.find(item => item.id === this.turnoverBatchRadio) || {}
      let endDate = dateArr[1]
      let startDate = dateArr[0]
      this.currentWorkStageList.forEach(item => {
        if (Date.parse(item.planDate[1]) > Date.parse(endDate)) {
          endDate = item.planDate[1]
        }
        if (Date.parse(item.planDate[0]) < Date.parse(startDate)) {
          startDate = item.planDate[0]
        }
      })
      currentBatch.planStartDate = startDate
      currentBatch.planEndDate = endDate
    },
    // 选中工单
    handleSelectionChange(val) {
      this.selectItems = val
      this.getCurrentWorkStage()
    },
    // 获取当前批次列表
    getCurrentWorkStage() {
      this.currentBatchList = this.turnoverBatchList.filter(item => this.selectItems.some(item1 => item.workorderId === item1.id)) || []
      if (this.currentBatchList.length) {
        this.turnoverBatchRadio = this.currentBatchList[0].id
      } else {
        this.turnoverBatchRadio = ''
      }
      this.getCurrentTurnoverBatch()
    },
    // 获取当前工序列表
    getCurrentTurnoverBatch() {
      this.currentWorkStageList = this.workorderWorkstageList.filter(item => item.turnoverBatchId === this.turnoverBatchRadio)
    },
    // 返回到上一步
    goBackPrev() {
      this.$emit('goBackPrev')
    },
    // 关闭弹窗
    closePage() {
      this.$emit('closePage')
    },
    // 关闭弹窗回调
    closeCallback() {
      this.turnoverBatchRadio = ''
      this.currentBatchList = []
      this.currentWorkStageList = []
    },
    // 工序时间禁选配置
    getPickerOptionsStart(workorderEnd) {
      let self = this
      return {
        disabledDate(time) {
          return time.getTime() < self.$startTimeStamp(window.serverTime) || time.getTime() > self.$endTimeStamp(workorderEnd)
        }
      }
    },
    // 计划开始\结束时间如果在今天之前，返回错误样式class
    errorDateClass(date) {
      return Date.parse(date) < this.$startTimeStamp(window.serverTime) ? 'error_date' : ''
    },
    // 格式化工序
    valitDate() {
      this.workorderWorkstageList.forEach(item => {
        item.startDate = item.planDate[0]
        item.endDate = item.planDate[1]
      })
    },
    // 提交拆分数据
    submitDivideData() {
      for (let i = 0; i < this.turnoverBatchList.length; i++) {
        let start = this.turnoverBatchList[i].planStartDate
        let end = this.turnoverBatchList[i].planEndDate
        if (!start || !end) {
          this.tipMessage('error', '计划时间不能为空')
          return
        } else if (Date.parse(start) < this.$startTimeStamp(window.serverTime)) {
          this.tipMessage('error', '计划开始时间不能早于系统当前时间')
          return
        }
      }
      this.valitDate()
      this.postSplitData(this.listData)
    },
    // 拆分请求
    postSplitData(postData) {
      this.isLoading = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorder/saveSplit',
        data: postData,
        noCommit: true
      }).then(() => {
        this.tipMessage('success', '提交成功')
        this.$emit('splitSuccess')
      }).finally(() => {
        this.isLoading = false
      })
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .split_preview {
    .el-dialog__body {
      padding-top: 0 !important;
    }

    .tables_panel {
      display: flex;
      padding: 20px 0;
    }

    .table_panel {
      height: auto;
      width: 33.3333%;
      border-right: @mesBorDefault;
      padding-right: 0 !important;
      padding-left: 15px !important;
      box-sizing: border-box;

      &:first-child {
        padding-left: 0 !important;
      }

      .table_title_item {
        text-align: center;
        line-height: 30px;
        border: @mesBorDefault;
        font-size: 13px;
        color: #333333;
        border-right: none;
      }

      .el-tabs__header {
        margin-bottom: 0;
      }

      .el-table--border {
        margin: 0 !important;
        height: 450px !important;
        border: none;

        th.gutter:last-of-type {
          border-right-color: #ebf0f6;
        }

        &::after {
          display: none;
        }
      }

      .el-table__body-wrapper {
        border-left: @mesBorDefault;
      }

      .el-table__header {
        border-left: @mesBorDefault;
        thead tr th:nth-last-child(2) {
          border-right: none !important;
        }
      }
      .el-table__body {
        padding: 0;
        tr {
          td {
            .cell {
              .el-radio {
                display: flex;
                width: 100%;
                height: 100%;
                align-items: center;
                justify-content: center;

                .el-radio__label {
                  display: none;
                }
              }

              .self_item {
                display: block;
                text-align: center;
                margin-left: -5px;
              }
            }

            .el-input__inner {
              padding: 0 0 0 20px !important;
              height: 100%;
              line-height: 36px;
              position: absolute;
              top: 0;
              left: 0;
              display: inline-block;
              margin-left: -5px;
              width: calc(100% + 5px);
            }

            .error_date {
              color: @mesTableInputEFC !important;
            }
          }

          .el-input__prefix {
            left: 0 !important;
          }

          .col_check .cell {
            padding: 0 !important;
          }
        }
      }
    }

    .turnoverList .table_dialog {
      td:last-child {
        border-right: none !important;
      }

      td.transparent_col {
        background-color: transparent !important;
      }
    }
  }
</style>
